//
//  TabBarController.swift
//  WB_Swift3.0
//
//  Created by wangrui on 2017/3/8.
//  Copyright © 2017年 wangrui. All rights reserved.
//

import UIKit

class TabBarController: UITabBarController
{
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    // 1. 使用代码控制设备的方向，好处是可以在需要横屏的时候单独处理
    // 2. 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
    // 3. 如果播放视频，通常是通过 modal 展现的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
    }
    
    @objc fileprivate func clickComposeButton()
    {
        print("点击撰写按钮")
        let vc = UIViewController()
        let nav = UINavigationController(rootViewController: vc)
        vc.title = "撰写微博"
        present(nav, animated: true, completion: {
            print("modal的方式弹出撰写控制器")
        })
    }
}

extension TabBarController
{
    fileprivate func setupComposeButton()
    {
        tabBar.addSubview(composeButton)
        let count = childViewControllers.count
        let width = tabBar.bounds.width / CGFloat(count) - 1
        composeButton.frame = tabBar.bounds.insetBy(dx: width * 2, dy: 0)
        composeButton.addTarget(self, action: #selector(clickComposeButton), for: .touchUpInside)
    }
    
    fileprivate func setupChildControllers()
    {
        // document文件中找main.json
        let documentFile = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = (documentFile as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: filePath)
        // 如果document文件中没有就在bundle中找
        if (data == nil) {
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            data = NSData(contentsOf: url ?? URL(fileURLWithPath: ""))
        }
        
        
        guard let array = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
            else {
            
            return
        }
        var arrM:[UIViewController] = [UIViewController]()
        for dict in array {
            arrM.append(viewController(dict: (dict)))
        }
        
        viewControllers = arrM
    }
    
    private func viewController(dict:[String:Any]) -> UIViewController
    {
        guard let clsName = dict["clsName"] as? String,
              let   title = dict["title"] as? String,
              let   image = dict["image"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? BaseViewController.Type,
              let visitorInfo = dict["visitorInfo"] as? [String:String]
        else {
            return UIViewController()
        }
        
        
        let vc = cls.init()
        vc.visitorView.visitorInfo = visitorInfo
        vc.title = title
        vc.tabBarItem.image = UIImage(named:image)
        vc.tabBarItem.selectedImage = UIImage(named: image + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14)], for: .normal)
        let nav = BaseNavigationController(rootViewController: vc)
        return nav
    }
    
}
